package com.example.dbbackupupload.timer;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ZipUtil;
import com.example.dbbackupupload.conifg.MyConfig;
import com.example.dbbackupupload.utils.DbBackup;
import com.example.dbbackupupload.utils.QiNiuUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * @Author Wlos
 * @Date 2025/3/14 12:07
 */
@Component
public class BackUploadTimer {
    @Resource
    private MyConfig myConfig;
    @Resource
    private QiNiuUtils qiNiuUtils;

    @Scheduled(cron = "0 0 3 * * *")
    public void backUpload() throws Exception {
        run();
    }

    public void run() throws Exception {
        for (String table : myConfig.getTables()) {
            String format = LocalDateTimeUtil.format(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss");
            System.out.println("--------------------------" + format + "---------------------------");
            System.out.println("备份表：" + table);
            TimeInterval timer = DateUtil.timer();
            String datePath = myConfig.getBackPath() + "/" + DateUtil.format(new Date(), "yyyy-MM-dd") + myConfig.getGroupName() + "/" + table + ".sql";
            System.out.println("备份路径：" + datePath);
            DbBackup.dbBackUp(myConfig.getUserName(), myConfig.getPassword(), table, datePath, myConfig.getMysqldumpPath());
            System.out.println("备份成功耗时：" + timer.intervalSecond() + "秒");
        }
        String format = LocalDateTimeUtil.format(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss");
        System.out.println("--------------------------" + format + "---------------------------");
        System.out.println("开始压缩文件");
        TimeInterval timer = DateUtil.timer();
        String zipPath = myConfig.getBackPath() + "/" + DateUtil.format(new Date(), "yyyy-MM-dd") + myConfig.getGroupName() + ".zip";
        ZipUtil.zip(myConfig.getBackPath() + "/" + DateUtil.format(new Date(), "yyyy-MM-dd") + myConfig.getGroupName(), zipPath);
        System.out.println("压缩成功耗时：" + timer.intervalSecond() + "秒 路径: " + zipPath);
        System.out.println("--------------------------" + format + "---------------------------");
        System.out.println("开始上传文件");
        String upload = qiNiuUtils.upload(zipPath, FileUtil.getName(zipPath));
        System.out.println("上传成功耗时：" + timer.intervalSecond() + "秒 结果: " + upload);
        System.out.println("--------------------------" + format + "---------------------------");
        System.out.println("开始删除文件");
        boolean del = FileUtil.del(zipPath);
        System.out.println("删除成功耗时：" + timer.intervalSecond() + "秒 结果: " + del);
    }
}
